package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.queryobject.EmployeeQueryObject;

import cn.wolfcode.resultpage.Json;
import cn.wolfcode.resultpage.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/stopOrrenew")
    @ResponseBody
    public JsonResult stopOrrenew(Long ids,boolean state){
        employeeService.updateState(ids,state);
        return new JsonResult();
    }


    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        // 文件下载的响应头(让浏览器访问资源的时候以下载的方式打开)
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        HSSFWorkbook workbook = employeeService.exportXls();
        // 输出到浏览器
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws Exception {
        // 将文件上传的数据以流的方式封装成workbook
        HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
        employeeService.importXls(workbook);
        return new JsonResult();

    }

    @RequestMapping("/checkName")
    @ResponseBody
    public Map<String,Boolean> checkName(Long id,String name){ // 前台插件要求返回键值对形式  (key)valid:(Boolean)true
        Map<String, Boolean> map = new HashMap<>();
        if(id != null){
            Employee selectById = employeeService.selectById(id);
            if(selectById.getName().equals(name)){
                map.put("valid",true);
                return map;
            }
        }
        //  判断用户名是否存在
        Employee employee = employeeService.checkName(name);

        /*if (employee != null){ // 不为空 已注册,
            map.put("valid",false);
        }else {
            map.put("valid",true);
        }*/
        map.put("valid",employee == null);
        return map;
    }


    // 管理员进行密码重置操作
    @RequestMapping("/rest")
    public String rest(Model model,Long id,HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        Employee User = (Employee)subject.getPrincipal();

        //Employee user = (Employee)session.getAttribute("USER_IN_SESSION");
        Employee employee = employeeService.selectOne(id);
        model.addAttribute("emp",employee);
        if (User.isAdmin()){
            return "/restPwd/resetPwd";
        }else{
            return "/common/nopermission";
        }
    }
    // 对用户进行密码重置操作
    @RequestMapping("/restPwd")
    @ResponseBody
    public JsonResult restPwd(Long id,String newPassword) {
        try {
            employeeService.restPwd(id, newPassword);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }

    // 使用重定向,跳转到修改密码的页面
    @RequestMapping("/jump")
    public String jump(){
        return "/updatePwd/updatePwd";
    }

    // 用户进行密码修改操作
    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword, String newPassword, HttpSession session){
        // 获取主体对象
        Subject subject = SecurityUtils.getSubject();
        // 将主体object类型强转为当前用户登录的类型employee
        Employee emp = (Employee)subject.getPrincipal();
        // Employee emp = (Employee)session.getAttribute("USER_IN_SESSION");
        try {
            employeeService.updatePassword(emp.getId(),oldPassword,newPassword);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }


    // 处理查询所有员工请求

    @RequiresPermissions("employee:list")
    @RequestMapping("/list")
    //@RequiredPermission(name="员工列表",expression="employee:list")
    // 把查询的方法的封装参数的形参改成 EmployeeQueryObject 类型,并贴上@ModelAttribute注解
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){
        // 调用分页查询的方法
        PageInfo<Employee> PageInfo = employeeService.query(qo);
        List<Department> departments = departmentService.listAll();
        // 往模型存数据
        model.addAttribute("PageInfo",PageInfo);
        model.addAttribute("departments",departments);
        // 找视图
        return "/employee/list";
    }

    // 处理删除请求
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null) {
            employeeService.delete(id);
        }
        // 本质让浏览器再发送一次请求到 http://localhost/employee/list.do
      return "redirect:/employee/list.do";
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id,Model model){
        // 需求: 新增员工时,部门不要输入而是选择
        List<Department> departments = departmentService.listAll();
        // 查询所有部门往模型存入,提供数据,让员工新增修改是显示出来以供用户选择
        model.addAttribute("departments",departments);

        //查询所有角色
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);


        if(id != null){ // 表示去修改
          Employee employee = employeeService.selectOne(id);
          model.addAttribute("employee",employee);
      }
      return "employee/input";
    }
    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee emp,Long[] ids) {

        try {
            if (emp.getId() != null){
                employeeService.update(emp,ids);
            }else {
                employeeService.insert(emp,ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"保存失败");
        }
    }

    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids){
        try {
            if (ids != null && ids.length > 0){ // 修改
                employeeService.deletes(ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"删除失败");
        }
    }
}
